#include "music.h"
#include <QJsonObject>
#include <QUrlQuery>
#include <QEventLoop>
#include "widget.h"
Music::Music(QObject *parent) : QObject(parent)
{
	music_manger = new QNetworkAccessManager(this);
    //music_request2= new QNetworkRequest(this);
    music_manager2 = new QNetworkAccessManager(this);
	qtaudioPlayer = new QMediaPlayer(this);
}
Music::~Music()
{

}

void Music::get_url()
{
   // ui->textEdit->clear();
    QString baseurl = "http://www.kugou.com/yy/index.php?/";
    QUrlQuery params;
    params.addQueryItem("r", "play/getdata");
    params.addQueryItem("hash", hash);//
    params.addQueryItem("album_id", songsid);
    params.addQueryItem("_", "1497972864535");
    QUrl api(baseurl);
    api.setQuery(params);

    QNetworkRequest request;
    request.setUrl(api);
    request.setRawHeader("Cookie","kg_mid=2333");
    QNetworkAccessManager *manger1 = new QNetworkAccessManager(this);
    QNetworkReply *pReplay =manger1->get(request);
    // 开启一个局部的事件循环，等待响应结束，退出
    QEventLoop eventLoop;
    QObject::connect(manger1, &QNetworkAccessManager::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();

    // 获取响应信息
    QByteArray bytes = pReplay->readAll();

    QString str = bytes.toStdString().data();
    //ui->textEdit->setText(str);

    music_url = str;
    parseJson_getplay_url(music_url);
}

void Music::parseJson_getAlbumID(QString json)     //解析接收到的歌曲信息，得到歌曲ID
{
    QByteArray byte_array;
    QJsonParseError json_error;
    QJsonDocument parse_doucment = QJsonDocument::fromJson(byte_array.append(json), &json_error);
    if(json_error.error == QJsonParseError::NoError)
    {
        if(parse_doucment.isObject())
        {
            QJsonObject rootObj = parse_doucment.object();
            if(rootObj.contains("data"))
            {
                QJsonValue valuedata = rootObj.value("data");
                if(valuedata.isObject())
                {
                    QJsonObject valuedataObject = valuedata.toObject();
                    if(valuedataObject.contains("lists"))
                    {                          
                        QJsonValue valueArray = valuedataObject.value("lists");
                        if (valueArray.isArray())
                        {
                            QJsonArray array = valueArray.toArray();

                                QJsonValue value = array.at(0);
                                if(value.isObject())
                                {
                                    QJsonObject object = value.toObject();
                                    if(object.contains("Grp"))
                                    {
                                        QJsonValue valueArray1 = object.value("Grp");
                                        if(valueArray1.isArray())
                                        {
                                            QJsonArray array1 = valueArray1.toArray();
                                               QJsonValue value1 = array1.at(0);
                                               QJsonObject obj = value1.toObject();
                                               QJsonValue hash_value = obj.take("FileHash");
                                               if(hash_value.isString())
                                               {
                                                   hash = hash_value.toString();
                                               }
                                               QJsonValue  songsid_value= obj.take("AlbumID");
                                               if(songsid_value.isString())
                                               {
                                                   songsid = songsid_value.toString();
                                               }                                            }

                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

    else
    {
        qDebug()<<json_error.errorString();
    }
}

void Music::parseJson_getplay_url(QString json)        //解析得到歌曲
{
    QByteArray byte_array;
    QJsonParseError json_error;
    QJsonDocument parse_doucment = QJsonDocument::fromJson(byte_array.append(json), &json_error);
    if(json_error.error == QJsonParseError::NoError)
    {
        if(parse_doucment.isObject())
        {
            QJsonObject rootObj = parse_doucment.object();
            if(rootObj.contains("data"))
            {
                QJsonValue valuedata = rootObj.value("data");
                if(valuedata.isObject())
                {
                    QJsonObject valuedataObject = valuedata.toObject();
                    QString play_urlStr("");
                    if(valuedataObject.contains("play_url"))
                    {
                        QJsonValue play_url_value = valuedataObject.take("play_url");
                        if(play_url_value.isString())
                        {
                            play_urlStr = play_url_value.toString();                    //歌曲的url

                            if(play_urlStr!="")
                            {
                                 music_urlvalue = play_urlStr;
                            }

                        }
                    }


                }
            }
        }
    }
}

int Music::play_music(QString music_name)
{
    QString name = music_name;
    name = name+"&page=&pagesize=&userid=-1&clientver=&platform=WebFilter&tag=em&filter=2&iscorrection=1&privilege_filter=0";
    // URL
    QString baseUrl = "http://songsearch.kugou.com/song_search_v2?keyword=";
    baseUrl = baseUrl+name;

    QNetworkRequest request;
    request.setUrl(QUrl(baseUrl));
       
    
    // 发送请求
    QNetworkReply *pReplay = music_manger->get(request);

    // 开启一个局部的事件循环，等待响应结束，退出
    QEventLoop eventLoop;
    QObject::connect(music_manger, &QNetworkAccessManager::finished, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();

    // 获取响应信息
    QByteArray bytes = pReplay->readAll();
    QString str = bytes.toStdString().data();
    parseJson_getAlbumID(str);
    get_url();
    if(music_urlvalue == "")
    {
        qDebug()<<"版权受限"<<endl;
        return 0;
    }
   test();
   return 1;
}

void Music::pause_music()
{
        qtaudioPlayer->pause();
}

void Music::append_music()
{
    qtaudioPlayer->play();
}
void Music::stop_music()
{
        qtaudioPlayer->stop();
}
void Music::voice_up()
{
    qtaudioPlayer->setVolume(qtaudioPlayer->volume()+50);
}
void Music::voice_down()
{
    qtaudioPlayer->setVolume(qtaudioPlayer->volume()-50);
}

void Music::test()
{
    QMediaPlaylist* playlist = new QMediaPlaylist(this);
      playlist->addMedia(QUrl(music_urlvalue));

      playlist->setCurrentIndex(1);


      qtaudioPlayer->setPlaylist(playlist);

      QVideoWidget *videoWidget = new QVideoWidget;
      qtaudioPlayer->setVideoOutput(videoWidget);
      //qtaudioPlayer->setMedia(QUrl::fromLocalFile(music_urlvalue));
      qtaudioPlayer->pause();
      qtaudioPlayer->play();
      connect(qtaudioPlayer,&QMediaPlayer::stateChanged,this,&Music::play_end);

}
void Music::play_end()
{
    emit play_finished();
}
